//
//  pulicMath.m
//  充电桩
//
//  Created by 李超杰 on 17/4/19.
//  Copyright © 2017年 李超杰. All rights reserved.
//
#define screenWidth [[UIScreen mainScreen] bounds].size.width
#define screenHeight [[UIScreen mainScreen] bounds].size.height
#import "pulicMath.h"
#import "PrefixHeader.pch"


@implementation pulicMath



//字符是否为空
-(BOOL)isBlankString:(NSString *)string{
    
    if (string == nil) {
            
            return NO;
            
        }
        
    if (string == NULL) {
        
        return NO;
        
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        
        return NO;
        
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        
        return NO;
        
    }
    
    return YES;
  
}

//判断手机号码格式是否正确
//- (BOOL)valiMobile:(NSString *)mobile
//
//{
//    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
//    if (mobile.length != 11)
//    {
//        return NO;
//    }else{
//        /**
//         * 移动号段正则表达式
//         */
//        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
//        /**
//         * 联通号段正则表达式
//         */
//        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
//        /**
//         * 电信号段正则表达式
//         */
//        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
//        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
//        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
//        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
//        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
//        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
//        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
//
//        if (isMatch1 || isMatch2 || isMatch3) {
//            return YES;
//        }else{
//            return NO;
//        }
//    }
//}
- (BOOL)valiMobile:(NSString *)mobile
{
    // 130-139  150-153,155-159  180-189  145,147  170,171,173,176,177,178
    NSString *phoneRegex = @"^((13[0-9])|(14[57])|(15[^4,\\D])|(16[0-9])|(18[0-9])|(19[0-9])|(17[013678]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
//密码判断
-(BOOL)checkPassWord:(NSString *)str
{
    //6-20位数字和字母组成
    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    if ([pred evaluateWithObject:str]) {
        return YES ;
    }else{
        return NO;
    }
    /*
    NSString * regex = @"^[A-Za-z0-9]{1,15}$";   //正则表达式
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];<br>    //Cocoa框架中的NSPredicate用于查询，原理和用法都类似于SQL中的where，作用相当于数据库的过滤取
    BOOL isMatch = [pred evaluateWithObject:userNameField.text];    //判读userNameField的值是否吻合
  */
    
}

-(NSString *)token{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    NSString *token = [user objectForKey:@"_x-access-token"];
    
    return token;
}
-(NSString *)version{
    
   NSString *string = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    return string;
}
//高德的key

-(NSString *)GDMap{
    
    NSString *str = @"da58aa79e1de100176c150309f96cdef";
//    NSString *str = @"9cc3e4b883a56c07adcfd846555a55eb";

    
    return str;
}

//判断是否登录，如果登录了就不执行，没登录就执行里面的方法
-(BOOL)checkLoagin{
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults] ;
    NSString *login = [user objectForKey:@"userName"];
    NSLog(@"login = %@",login);
    if ([self isBlankString:login]) {
        
        return YES;
    }
    return NO;
}
-(void)exitLoagin{
    
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc]init];
    //向友盟清除userid；
    NSString *userid = [userDefaults valueForKey:@"userId"];
    [self removeUMAliasuserid:userid];
    
    [userDefaults removeObjectForKey:@"_x-access-token"];
    [userDefaults removeObjectForKey:@"cellPhone"];
    [userDefaults removeObjectForKey:@"headPicture"];
    [userDefaults removeObjectForKey:@"idNo"];
    [userDefaults removeObjectForKey:@"isHadBankCard"];
    [userDefaults removeObjectForKey:@"isHadTradingPassword"];
    [userDefaults removeObjectForKey:@"nickName"];
    [userDefaults removeObjectForKey:@"realName"];
    [userDefaults removeObjectForKey:@"sex"];
    [userDefaults removeObjectForKey:@"userId"];
    [userDefaults removeObjectForKey:@"userName"];
    [userDefaults removeObjectForKey:@"isHadPassWord"];
    [userDefaults removeObjectForKey:@"unReadCount"];
    
}

- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
-(UIImageView *)loadingGifImage
{
 
    NSString  *name = @"加载.gif";
    
    NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    
    NSData  *imageData = [NSData dataWithContentsOfFile:filePath];
    
    UIImageView *loadingImageView = [[UIImageView alloc] init];
    
    loadingImageView.backgroundColor = [UIColor clearColor];
    
    loadingImageView.image = [self gifChangeToImageWithData:imageData];
    
//    loadingImageView.frame = CGRectMake(50, 50, screenWidth-100 , screenWidth-100);
    
    
    
    [self configUI:loadingImageView];
    
    return loadingImageView;
}
- (UIImage *)gifChangeToImageWithData:(NSData *)data

{
    
    if (!data)
        
    {
        
        return nil;
        
    }
    
    
    
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    
    
    
    size_t count = CGImageSourceGetCount(source);
    
    
    
    UIImage *animatedImage;
    
    
    
    if (count <= 1)
        
    {
        
        animatedImage = [[UIImage alloc] initWithData:data];
        
    }
    
    else
        
    {
        
        NSMutableArray *images = [NSMutableArray array];
        
        
        
        NSTimeInterval duration = 0.1f;
        
        
        
        for (size_t i = 0; i < count; i++)
            
        {
            
            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
            
            if (!image)
                
            {
                
                continue;
                
            }
            
            
            
            duration += [self frameDurationAtIndex:i source:source];
            
            
            
            [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
            
            
            
            CGImageRelease(image);
            
        }
        
        
        
        if (!duration)
            
        {
            
            duration = (1.0f / 10.0f) * count;
            
        }
        
        
        
        animatedImage = [UIImage animatedImageWithImages:images duration:duration];
        
    }
    
    
    
    CFRelease(source);
    
    
    
    return animatedImage;
    
}



- (void)configUI:(UIImageView *)loadingImageView

{
    
    
    
    //    loadingImageView.center = CGPointMake(400 / 2, 400 / 2);
    
    loadingImageView.tag = 0xadd;
    
    //    [self addSubview:loadingImageView];
    
    
    
}



- (float)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source

{
    
    float frameDuration = 0.1f;
    
    CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    
    NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
    
    NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
    
    
    
    NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    
    if (delayTimeUnclampedProp)
        
    {
        
        frameDuration = [delayTimeUnclampedProp floatValue];
        
    }
    
    else
        
    {
        
        NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
        
        if (delayTimeProp)
            
        {
            
            frameDuration = [delayTimeProp floatValue];
            
        }
        
    }
    
    if (frameDuration < 0.011f)
        
    {
        
        frameDuration = 0.100f;
        
    }
    
    CFRelease(cfFrameProperties);
    
    return frameDuration;
    
}
//旋转动画
- (UIImageView *)circleBasicAnimation
{
    
    // 基本动画
    // 1.创建核心动画的对象
    CABasicAnimation* anim = [[CABasicAnimation alloc] init];
    //    self.anim = anim;
    anim.delegate = self;
    // 2.设置核心动画的操作
    anim.keyPath = @"transform.rotation";
    
    //    anim.fromValue = @(100); // 从哪
    //    anim.toValue = @(300); // 到哪
    
    anim.byValue = @(2 * M_PI);
    
    anim.duration = 1;
    
    anim.repeatCount = INT_MAX; // 重复次数
    
    // 动画完毕以后不回到原来的位置
    anim.fillMode = kCAFillModeForwards;
    anim.removedOnCompletion = NO;
    
    // 3.添加到layer上
    UIImageView *ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    ImageView.image = [UIImage imageNamed:@"加载转动"];
    [ImageView.layer addAnimation:anim forKey:nil];
    
    
    
//    NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"加载" ofType:@"gif"]];
//    UIImage *image = [UIImage sd_animatedGIFWithData:data];
//
//    //自定义imageView
//    UIImageView *ImageView = [[UIImageView alloc] initWithImage:image];

    
    
    return ImageView;
}

//生成二维码
-(UIImage *)getQR:(NSString *)string
{
    
    // 1.创建过滤器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复默认
    [filter setDefaults];
    // 3.给过滤器添加数据
    //    NSString *dataString = @"http://www.baidu.com";
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    // 4.通过KVO设置滤镜inputMessage数据
    [filter setValue:data forKeyPath:@"inputMessage"];
    // 4.获取输出的二维码
    CIImage *outputImage = [filter outputImage];
    // 5.将CIImage转换成UIImage，并放大显示
    //    self.QRcodeImg.image = [UIImage imageWithCIImage:outputImage scale:20.0 orientation:UIImageOrientationUp];
    
    return  [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:160];
    
    
}
//重画二维码  变清晰
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    
    //设置比例
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 创建bitmap（位图）;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    
    
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
    
}
#pragma mark 获取字符串宽高 value-待计算字符串 fontSize-字体大小 WHmake-控件宽高
-(CGRect) widthForString:(NSString *)value fontSize:(float)fontSize andWH:(CGSize)WHmake
{
    
    CGRect labelsize =[value boundingRectWithSize:WHmake options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil];
    
    
    
    return labelsize;
    
}
//写数据
- (void)writeLocalCacheData:(NSData *)data withKey:(NSString *)key {
    
    // 设置存储路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]
                            stringByAppendingPathComponent:key];
    
    // 判读缓存数据是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {
        
        // 删除旧的缓存数据
        NSLog(@"删除旧的缓存数据");
        NSLog(@"%@",cachesPath);
        [[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
    }
    
    // 存储新的缓存数据
    [data writeToFile:cachesPath atomically:YES];
}
//读数据
- (NSData *)readLocalCacheDataWithKey:(NSString *)key {
    
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]
                            stringByAppendingPathComponent:key];
    
    // 判读缓存数据是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {
        
        // 读取缓存数据
        return [NSData dataWithContentsOfFile:cachesPath];
    }
    
    return nil;
}
@end
